import jwt from 'jsonwebtoken'
import RedisServer from "./redis";
import {tokenParams} from "../../global"

// 生成token
export const generateToken = async <T extends object>(params: T, email: string): Promise<string> => {
    const token: string = jwt.sign(params, process.env.NODE_JWT_SECRETKEY as string)
    await RedisServer.redisSet(`token:${email}`, token)
    return token
}
export type IParseToken = (tokenParams | { error: any }) & { code: number }
// 解析token
export const parseToken = (token: string): IParseToken => {
    try {
        return { code: 200, ...jwt.verify(token, process.env.NODE_JWT_SECRETKEY as string, { algorithms: ['HS256'] }) as tokenParams }
    } catch (e) {
        return { code: 500, error: e }
    }
}
